package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 方法上加文档注释
     * 查询所有功能
     *
     * @return
     */
    public List<Brand> selectAll() {
        //调用BrandMapper.selectAll()方法

        //1.获得工厂
//        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//        因为每一个功能都会使用这段SqlSesionfactoy的初始化，所以将这段代码提升到成员的位置
        //2.获得sqlsession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.mapper调用selectAll（）
        List<Brand> brands = mapper.selectAll();

        sqlSession.close();
        return brands;
    }

    /**
     * 添加
     */
    public void add(Brand brand) {
        //2.获得sqlsession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.mapper调用insert()
        mapper.add(brand);

        //因为是增删改的方法之一,所以要提交事务
        sqlSession.commit();
        //关闭资源
        sqlSession.close();

    }

    /**
     * 根据id查找
     * @param id
     */

    public Brand selectById(int id) {
        //调用BrandMapper.selectAll()方法

        //1.获得工厂
//        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//        因为每一个功能都会使用这段SqlSesionfactoy的初始化，所以将这段代码提升到成员的位置
        //2.获得sqlsession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.mapper调用selectAll（）
        Brand brand = mapper.selectById(id);

        sqlSession.close();
        return brand;
    }

    /**
     * 修改/更新
     */
    public void update(Brand brand) {
        //2.获得sqlsession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.mapper调用update()
        mapper.update(brand);

        //因为是增删改的方法之一,所以要提交事务
        sqlSession.commit();
        //关闭资源
        sqlSession.close();

    }

    /**
     * 删除
     */
    public void deleteById(int id){

        //2.获得sqlsession
        SqlSession sqlSession = factory.openSession();
        //3.获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.mapper调用delete()
        mapper.deleteById(id);
        //因为是增删改之一，所以要提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();

    }
}
